import { defineStore } from "pinia"
import { computed, ref } from 'vue'
import { findNewCartListAPI, insertCartAPI,deleteCartAPI } from "@/apis/cart"
import { useUserStore } from "./user"
export const useCartStore = defineStore('cart', () => {
    const userStore = useUserStore()
    const isLogin = computed(() => userStore.userInfo.token) //注意此处要用计算属性
    const cartList = ref([])
    // 添加购物车操作
    // 已添加过 - count + count
    // 没有添加过 - 直接push
    // 思路：通过匹配传递过来的商品对象中的skuId能不能在cartList中找到，找到了就是添加过

    const addCart = async (good) => {
        const { skuId, count } = good
        if (isLogin.value) {
            await insertCartAPI({ skuId, count })
            const { data: res } = await findNewCartListAPI()
            cartList.value = res.result
        } else {
            const item = cartList.value.find(item => item.skuId === good.skuId)
            if (item) {
                item.count += good.count
            } else {
                cartList.value.push(good)
            }
        }
    }
    //删除购物车
    const delCart = async(skuId) => {
        if(isLogin.value){
           await deleteCartAPI([skuId])
           const { data: res } = await findNewCartListAPI()
           cartList.value = res.result
        }else{
            const index = cartList.value.findIndex(item => item.skuId === skuId)
            if (index >= 0) {
                cartList.value.splice(index, 1)
            }
        }
        
    }

    //计算总商品数(计算属性)
    const allCount = computed(() => cartList.value.reduce((a, c) => a + c.count, 0))
    //计算总商品价格
    const allPrice = computed(() => cartList.value.reduce((a, c) => a + c.count * c.price, 0))
    //计算已选择商品数
    const selectedCount = computed(() => cartList.value.filter(item => item.selected == true).reduce((a, c) => a + c.count, 0))
    const selectedPrice = computed(() => cartList.value.filter(item => item.selected == true).reduce((a, c) => a + c.count * c.price, 0))
    //单选操作
    const singleCheck = (skuId, selected) => {
        const item = cartList.value.find(item => item.skuId === skuId)
        if (item) {
            item.selected = selected
        }
    }
    //全选功能
    const isAll = computed(() => cartList.value.every(item => item.selected === true))
    const allCheck = (selected) => cartList.value.forEach(item => item.selected = selected)

    //清空购物车
    const clearCart = ()=>{
        cartList.value = []
    }
    return {
        cartList,
        allCount,
        allPrice,
        isAll,
        selectedCount,
        selectedPrice, 
        allCheck,
        addCart,
        delCart,
        singleCheck,
        clearCart

    }
},
    {
        persist: true
    }
)